package com.klm.controller;

import com.klm.cache.CacheStats;
import com.klm.cache.TranslateCacheManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wq
 */
@Slf4j
@RestController
@RequestMapping("/api/cache")
public class CacheMonitorController {
    
    @Autowired
    private TranslateCacheManager cacheManager;
    
    @GetMapping("/stats")
    public CacheStats getCacheStats() {
        return cacheManager.getCacheStats();
    }
    
    @GetMapping("/metrics")
    public Map<String, Object> getCacheMetrics() {
        CacheStats stats = cacheManager.getCacheStats();
        Map<String, Object> metrics = new HashMap<>();
        
        // 基础指标
        metrics.put("hitRate", stats.getHitRate());
        metrics.put("errorRate", stats.getErrorRate());
        metrics.put("warmUpSuccessRate", stats.getWarmUpSuccessRate());
        metrics.put("batchSuccessRate", stats.getBatchSuccessRate());
        
        // 性能指标
        metrics.put("averageRefreshTime", stats.getAverageRefreshTime());
        metrics.put("averageGetTime", stats.getAverageGetTime());
        metrics.put("maxRefreshTime", stats.getMaxRefreshTime());
        metrics.put("maxGetTime", stats.getMaxGetTime());
        
        // 容量指标
        metrics.put("currentSize", stats.getCurrentSize());
        metrics.put("maxSize", stats.getMaxSize());
        metrics.put("evictionCount", stats.getEvictionCount());
        
        return metrics;
    }
    
    @GetMapping("/health")
    public Map<String, Object> getCacheHealth() {
        CacheStats stats = cacheManager.getCacheStats();
        Map<String, Object> health = new HashMap<>();
        
        // 健康状态
        health.put("status", calculateHealthStatus(stats));
        health.put("lastRefreshTime", stats.getLastRefreshTime());
        health.put("lastErrorTime", stats.getLastErrorTime());
        health.put("lastEvictionTime", stats.getLastEvictionTime());
        health.put("lastWarmUpTime", stats.getLastWarmUpTime());
        
        // 错误信息
        health.put("lastErrorMessage", stats.getLastErrorMessage());
        
        return health;
    }
    
    @PostMapping("/refresh")
    public Map<String, Object> refreshCache() {
        Map<String, Object> result = new HashMap<>();
        try {
            cacheManager.refreshAllCache();
            result.put("success", true);
            result.put("message", "Cache refresh initiated successfully");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Failed to refresh cache: " + e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/warm-up")
    public Map<String, Object> warmUpCache() {
        Map<String, Object> result = new HashMap<>();
        try {
            cacheManager.warmUpCache();
            result.put("success", true);
            result.put("message", "Cache warm-up initiated successfully");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Failed to warm up cache: " + e.getMessage());
        }
        return result;
    }
    
    private String calculateHealthStatus(CacheStats stats) {
        if (stats.getErrorRate() > 0.1) { // 错误率超过10%
            return "UNHEALTHY";
        }
        if (stats.getHitRate() < 0.5) { // 命中率低于50%
            return "DEGRADED";
        }
        return "HEALTHY";
    }
} 